package fr.univ.context.data.info;

import java.io.File;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

public class MemorySize {

	public static final int ERROR = -1;
	
	public static boolean externalMemoryAvailable() {
	    
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}
	
	public static long getAvailableInternalMemorySize() {
		
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return availableBlocks * blockSize;
	}
	
	public static long getAvailableExternalMemorySize() {
		
		if(externalMemoryAvailable()) {
			File path = Environment.getExternalStorageDirectory();
			StatFs stat = new StatFs(path.getPath());
			long blockSize = stat.getBlockSize();
			long availableBlocks = stat.getAvailableBlocks();
			return availableBlocks * blockSize;
		} else {
			return ERROR;
		}
	}
	
	public static long getAvailableMemoryRAM(Context ctx){
		
		MemoryInfo mi = new MemoryInfo();
		ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
		activityManager.getMemoryInfo(mi);
		return mi.availMem ;	
	}
	
	public static String formatSize(long size) {
		
		String suffix = null;
	
		if (size >= 1024) {
			suffix = "KiB";
			size /= 1024.0;
			
			if (size >= 1024) {
				suffix = "MiB";
				size /= 1024.0;
				
				if (size >= 1024) {
					suffix = "GiB";
					size/= 1024.0;
				}
			}			
		}
	
		StringBuilder resultBuffer = new StringBuilder(Long.toString(size));
	
		int commaOffset = resultBuffer.length() - 3;
		
		while (commaOffset > 0) {
			resultBuffer.insert(commaOffset, ',');
			commaOffset -= 3;
		}
	
		if (suffix != null)
			resultBuffer.append(suffix);
		return resultBuffer.toString();
	}
}